<template>
  <form>
    <div v-for="field in fields" :key="field.id" style="margin-bottom:12px" :ref="el => setFieldRef(el, field)">
      <input v-if="field.type==='input'" v-model="field.value" placeholder="普通输入"/>
      
      <select v-else-if="field.type==='select'" v-model="field.value">
        <option v-for="opt in field.options" :key="opt" :value="opt">{{ opt }}</option>
      </select>
      
      <div v-else-if="field.type==='rich'" class="rich-wrapper">
        <div v-if="!field.loaded" style="min-height:200px; border:1px dashed #ccc; display:flex;align-items:center;justify-content:center;">
          富文本加载中...
        </div>
        <component v-else :is="RichTextEditor" v-model="field.value"/>
      </div>
    </div>
  </form>
</template>

<script setup>
import { ref, defineAsyncComponent, onMounted, nextTick  } from 'vue'

const RichTextEditor = defineAsyncComponent(() => import('./RichTextEditor.vue'))

const fields = ref(
  Array.from({ length: 50 }, (_, i) => {
    if (i % 5 === 0) return { id: i, type: 'rich', value: '', loaded: false }
    else if (i % 2 === 0) return { id: i, type: 'select', value: '', options: ['A','B','C'] }
    else return { id: i, type: 'input', value: '' }
  })
)
// 存储 DOM 元素
const fieldEls = ref([])

// IntersectionObserver
let observer = null

function setFieldRef(el, field) {
  if (!el || field.loaded) return
  fieldEls.value.push({ el, field })
}

onMounted(async () => {
  await nextTick()
  if (!observer) {
    observer = new IntersectionObserver((entries) => {
       entries.forEach(entry => {
         if (entry.isIntersecting) {
            const item = fieldEls.value.find(f => f.el === entry.target)
            if (item) {
              item.field.loaded = true
              observer.unobserve(entry.target)
            }
         }
       })
    }, { rootMargin: '100px' })
  }
  // 注册所有 DOM 元素
  fieldEls.value.forEach(({ el }) => observer.observe(el))
})
</script>
